package com.interviewbackend.client;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletionCreateParams;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class QuestionGenerationClient {

    @Value("${qwen.api.key}")
    private String apiKey;

    @Value("${qwen.api.url}")
    private String apiUrl;

    @Value("${qwen.model.name}")
    private String modelName;

    private OpenAIClient client;

    @PostConstruct
    public void init() {
        client = OpenAIOkHttpClient.builder()
                .apiKey(apiKey)
                .baseUrl(apiUrl)
                .build();
    }

    public String generateQuestionFromPrompt(String prompt) {
        try {
            ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                    .model(modelName)
                    .addUserMessage(prompt)
                    .build();

            ObjectMapper mapper = new ObjectMapper();
            System.out.println("🔥 调用模型：" + modelName);
            System.out.println("🔥 请求 Prompt：" + prompt);

            Object raw = client.chat().completions().create(params);
            Map<String, Object> resultMap = mapper.convertValue(raw, Map.class);

            List<Map<String, Object>> choices = (List<Map<String, Object>>) resultMap.get("choices");
            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                if (message != null && message.get("content") != null) {
                    return message.get("content").toString().trim();
                }
            }
            return "【AI生成失败：未提取到内容】";
        } catch (Exception e) {
            e.printStackTrace();
            return "【AI生成失败，请稍后再试】";
        }
    }
}
